let sn_button_houseId;
function init(process) {
    layui.use(['form', 'layedit', 'laydate','element','laytpl'], function(){
        var form = layui.form
            ,layer = layui.layer
            ,laytpl = layui.laytpl
            ,laydate = layui.laydate;

        imgListener();

        getByType(_baseUrl,ORDER_TYPE.SP.type, $("[name='no']"));
        $(".reloadNo").click(function () {
            getByType(_baseUrl,ORDER_TYPE.SP.type, $("[name='no']"),true);
        });
        ajaxSelect(_baseUrl+"goods/type/getAll.action",'typeId');
        ajaxSelect(_baseUrl+"goods/unit/getAll.action",'unitId0',null,function (data) {
            setUnitList(data);
            processCodeDiv();
            processPriceDiv();

            if (getGoods().oper == 'update') {
                update_init();
            }
        });

        $(".closeSelf").click(function () {
            closeSubIframe();
        });

        $(".save").click(function () {
            $("#submit").click();
        });

        $("#add-unit").click(function () {
            let goods = getGoods();
            if (isTrue(goods.sn)) {
                errTip("已开启序列号，不能启用副单位");
                return;
            }

            let unitCount = parseInt(goods.unitCount);
            if (unitCount>3) {
                errTip("最多只能有3个副单位");
                return;
            }

            var getTpl = second_unit.innerHTML;
            laytpl(getTpl).render(goods, function(html){
                $("#second-unit-div").append(html);
                formRender();
                $('[name="unitCount"]').val(unitCount + 1);

                $(".deleteSecondUnit").unbind("click").click(function () {
                    $(this).parent().parent().remove();
                    let unitCount = parseInt(getGoods().unitCount);
                    $('[name="unitCount"]').val(unitCount - 1);

                    $.each($("#second-unit-div .layui-form-item"),function (i, e) {
                        var index = i+1;
                        $(e).find(".layui-form-label span").html("副单位"+index);
                        $(e).find(".unitSelect").attr("name","unitId" + index);
                        $(e).find(".times").attr("name","times" + index);
                    });
                    formRender();
                    processCodeDiv();
                    processPriceDiv();
                });

                processCodeDiv();
                processPriceDiv();
            });
        });

        $(".sn-init-button").click(function () {
            if(isTrue(getGoods().used)) {
                confirm("该序列号商品被单据引用，无法修改期初信息.\n若您的期初序列号录入有误，建议通过盘点功能修正。");
                return;
            }

            sn_button_houseId = $(this).attr("hid");
            let snList = JSON.parse($("#"+sn_button_houseId).attr("snList"));
            if (emptyList(snList)) {
                snList=[];
            }

            openHtmlDialog("管理序列号",_baseUrl+"dialog/sn/import.action?goodsId="+getGoods().id+"&houseId="+sn_button_houseId, function (layero, index) {
                var iframe = window[layero.find('iframe')[0]['name']];
                // console.log("已经有序列号了，加载完窗口后，需要重载现有的数据:"+ JSON.stringify(snData));
                iframe.setDataToTable(snList,genUseMap());
            });
        });

        form.on('checkbox(moreAttr)', function(data){
            if(data.elem.checked) {
                $("#attr-div").css("display","block");
            }else{
                $("#attr-div").css("display","none");
            }
        });

        form.on('select', function(data){
            if($(data.elem).hasClass("unitSelect")) {
                if (isTrue(getUnit(data.value).point) && isTrue(getGoods().sn)) {
                    errTip("你已开启序列号，不能选择有小数的单位,自动切换到不允许单位的小数");
                    console.log(getGoods()[$(data.elem).attr("name")]);
                    console.log($(data.elem).attr("name"));
                    $(data.elem).val(getUnitList()[0].id);
                    formRender();
                    return;
                }
                processCodeDiv();
                processPriceDiv();

                let unit = getUnit(getGoods().unitId0);
                $(".baseUnitName").html(unit.name);
                if (!unit.point) {
                    $(".initNum,.minHouse,.maxHouse").each(function (i,e) {
                        $(e).val( parseInt($(e).val()) );
                    });
                }
            }
        });

        form.on('radio(sn)', function(data){
            if(isTrue(data.value)) {
                if ($(".unitSelect").length >1) {
                    errTip("你已开启多单位，不允许启用序列号");
                    $("input[name='sn'][value='true']").prop("checked", false);
                    $("input[name='sn'][value='false']").prop("checked",true);
                    form.render();
                    return;
                }

                let unit = getUnit(getGoods().unitId0);
                if (unit.point) {
                    errTip("你选择的单位允许小数，不允许启用序列号");
                    $("input[name='sn'][value='true']").prop("checked", false);
                    $("input[name='sn'][value='false']").prop("checked",true);
                    form.render();
                    return;
                }

                if (isTrue(getGoods().used)){
                    tip("商品被业务单据引用，无法开启序列号");
                    $("input[name='sn'][value='true']").prop("checked", false);
                    $("input[name='sn'][value='false']").prop("checked",true);
                    form.render();
                    return;
                }
            }

            if(isTrue(data.value)) {
                $(".initNum").addClass("readonly").attr("readonly", "readonly").next().css("display", "block");
            } else {
                $(".initNum").removeClass("readonly").removeAttr("readonly").next().css("display", "none");
            }
        });

        //自定义验证规则
        form.verify({
            no: function(value){
                if(emptyEntity(value)){
                    return '编号不能为空';
                }
            }
            ,typeId: function(value){
                if(emptyEntity(value)){
                    return '分类不能为空';
                }
            }
            ,unitId0: function(value){
                if(emptyEntity(value)){
                    return '基本单位不能为空';
                }
            }
            ,unitId1: function(value){
                if(emptyEntity(value)){
                    return '副单位1不能为空';
                }
            }
            ,unitId2: function(value){
                if(emptyEntity(value)){
                    return '副单位2不能为空';
                }
            }
            ,unitId3: function(value){
                if(emptyEntity(value)){
                    return '副单位3不能为空';
                }
            }
            ,times: function(value){
                if(emptyEntity(value)){
                    return '副单位的换算倍数不能为空';
                }
                if (!emptyEntity(value) && !/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/.test(value)) {
                    return '必须是正数';
                }

                if (parseFloat(value) > 1000 || parseFloat(value)<=1) {
                    return '请输入正确的副单位换算倍数, 换算倍数需为1到10000间的数值，且不能等于1';
                }
            }
            ,positive: function (value) {
                if (!emptyEntity(value) && !/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/.test(value)) {
                    return '必须是正数';
                }
            }
            ,point: function (value) {
                let unit = getUnit(getGoods().unitId0);
                if (!emptyEntity(value) && !unit.point && value.indexOf(".")!=-1) {
                    return '单位('+unit.name+'),不支持小数';
                }
            }
            ,initNum: function (value) {
                if (!emptyEntity(value) && !/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/.test(value)) {
                    return '初期数量必须是正数';
                }

                let unit = getUnit(getGoods().unitId0);
                if (!emptyEntity(value) && !unit.point && value.indexOf(".")!=-1) {
                    return '单位('+unit.name+'),不支持小数';
                }
            }
            ,point: function (value) {
                let unit = getUnit(getGoods().unitId0);
                if (!emptyEntity(value) && !unit.point && value.indexOf(".")!=-1) {
                    return '单位('+unit.name+'),不支持小数';
                }
            }

        });

        form.on("submit(goods)",function (data) {
            let entity = data.field;
            var goods = {};


            //如果开启sn，则要检查sn序列号数量与initNum是否一致
            if (isTrue(entity.sn)) {
                let flag = false;
                $(".snList").each(function (i,elem) {
                    let initNum = getNumber(entity['initNum'+i]);
                    let snList = JSON.parse($(elem).attr("snList"));
                    if (initNum != snList.length) {
                        flag = true;
                        return false;
                    }
                });
                if (flag) {
                    errTip("初期序列号数量与初期库存数量不一致，请检查");
                    return false;
                }
            }

            for(var i=0; i<entity.houseCount;i++){
                //大于0时才会新增
                let min = getNumber(entity['minHouse'+i]);
                let max = getNumber(entity['maxHouse'+i]);
                if (min > max) {
                    errTip("库存预警最低值不能高于最高值");
                    return false;
                }
            }



            goods.id = entity.id;
            goods.name = entity.name;
            goods.no = entity.no;
            goods.norms = entity.norms;
            goods.typeId = entity.typeId;
            goods.status = entity.status;
            goods.remark = entity.remark;
            var imgName = $("#goods-img").attr("imgName");
            goods.image = (imgName == "" || imgName==undefined) ? "" : imgName;

            goods.goodsHouseWarnList = [];
            goods.goodsInitList = [];
            for(var i=0; i<entity.houseCount;i++){
                //大于0时才会新增
                if (getNumber(entity['minHouse'+i])>0 || getNumber(entity['maxHouse'+i])>0) {
                    var goodsHouseWarn = {};
                    goodsHouseWarn.houseId = entity['houseId'+i];
                    goodsHouseWarn.goodsId = entity.id;
                    goodsHouseWarn.min = getNumber(entity['minHouse'+i]);
                    goodsHouseWarn.max = getNumber(entity['maxHouse'+i]);
                    goods.goodsHouseWarnList.push(goodsHouseWarn);
                }

                if (getNumber(entity['initNum'+i])>0) {
                    var goodsInit = {};
                    goodsInit.houseId = entity['houseId'+i];
                    goodsInit.goodsId = entity.id;
                    goodsInit.initNum = getNumber(entity['initNum'+i]);
                    goodsInit.initCost = getNumber(entity['initCost'+i]);
                    goodsInit.initAmt = getNumber(entity['initAmt'+i]);
                    goods.goodsInitList.push(goodsInit);
                }
            }

            if (isTrue(entity.sn)) {
                //处理序列号
                goods.initGoodsSnList = [];
                $(".snList").each(function (i,elem) {
                    let snList = JSON.parse($(elem).attr("snList"));
                    $.each(snList, function (i,d) {
                        delete d.LAY_TABLE_INDEX;
                        goods.initGoodsSnList.push(d);
                    });
                });
            }

            goods.goodsUnitList = [];
            var unitCount  = parseInt(entity.unitCount);
            for (var i=0; i < unitCount; i++){
                var goodsUnit = {};
                goodsUnit.goodsId = entity.id;
                goodsUnit.unitId = entity['unitId'+i];
                goodsUnit.base = i==0?true:false;
                goodsUnit.times = entity['times'+i];
                goodsUnit.code = entity['code'+i];
                goodsUnit.retailPrice = getPrice(getNumber(entity['retailPrice'+i]));
                goodsUnit.wholesalePrice = getPrice(getNumber(entity['wholesalePrice'+i]));
                goodsUnit.minPrice = getPrice(getNumber(entity['minPrice'+i]));
                goodsUnit.referBuyPrice = getPrice(getNumber(entity['referBuyPrice'+i]));
                goods.goodsUnitList.push(goodsUnit);
            }

            if (isTrue(entity.moreAttr)) {
                var attrNameCount  = parseInt(entity.attrNameCount);
                goods.goodsAttrList = [];
                for (var i=0; i < attrNameCount; i++){
                    var goodsAttr = {};
                    var id = entity['attr'+i];
                    if (emptyEntity(id)){
                        continue;
                    }
                    goodsAttr.attrId = id;
                    goodsAttr.goodsId = entity.id;
                    goods.goodsAttrList.push(goodsAttr);
                }
            }

            if (isTrue(entity.sn)){
                goods.sn = true;
            }else {
                goods.sn = false;
            }

            console.log(JSON.stringify(goods));
            tipLoad();
            $(".save").parent().hide();

            if (entity.oper == 'update') {
                post(_baseUrl+"goods/goods/update.action",goods,function (resp) {
                    closeAll();
                    $(".save").parent().show();
                    if (resp.code == 1){
                        refreshMainIframe(_baseUrl+"goods/goods.action");
                        tip('新增成功');
                        closeSubIframe();
                    } else {
                        errTip(resp.msg);
                    }
                });
            } else {
                post(_baseUrl+"goods/goods/insert.action",goods,function (resp) {
                    closeAll();
                    $(".save").parent().show();
                    if (resp.code == 1){
                        refreshMainIframe(_baseUrl+"goods/goods.action");
                        tip('新增成功');
                        closeSubIframe();
                    } else {
                        errTip(resp.msg);
                    }
                });
            }
            return false;
        });

        function update_init(goodsVo) {
            get(_baseUrl+"goods/goods/findVoById.action?id="+getGoods().id, function (res) {
                if (res.code != 1) {
                    errTip("获取商品信息失败");
                    return;
                }

                if(isTrue(getGoods().used)) {
                    $(".initNum").addClass("readonly").attr("readonly", "readonly");
                    $(".initCost").addClass("readonly").attr("readonly", "readonly");
                    $(".initAmt").addClass("readonly").attr("readonly", "readonly");
                }

                let goodsVo = res.data;
                if (goodsVo.sn) {
                    $(".initNum").addClass("readonly").attr("readonly", "readonly").next().css("display", "block");
                }

                let initData = {};
                initData.typeId = goodsVo.typeId;

                //处理单位
                var getTpl = init_unit.innerHTML;
                laytpl(getTpl).render(goodsVo.goodsUnitVoList, function(html){
                    $("#second-unit-div").append(html);
                    formRender();
                    $('[name="unitCount"]').val(goodsVo.goodsUnitVoList.length);

                    $(".deleteSecondUnit").unbind("click").click(function () {
                        $(this).parent().parent().remove();
                        let unitCount = parseInt(getGoods().unitCount);
                        $('[name="unitCount"]').val(unitCount - 1);

                        $.each($("#second-unit-div .layui-form-item"),function (i, e) {
                            var index = i+1;
                            $(e).find(".layui-form-label span").html("副单位"+index);
                            $(e).find(".unitSelect").attr("name","unitId" + index);
                            $(e).find(".times").attr("name","times" + index);
                        });
                        formRender();
                        processCodeDiv();
                        processPriceDiv();
                    });

                    processCodeDiv();
                    processPriceDiv();

                    $.each(goodsVo.goodsUnitVoList, function (i,d) {
                        initData['unitId'+i] = d.unitId;
                        initData['code'+i] = d.code;
                        initData['times'+i] = d.times;
                        initData['retailPrice'+i] = getPrice(d.retailPrice);
                        initData['wholesalePrice'+i] = getPrice(d.wholesalePrice);
                        initData['minPrice'+i] = getPrice(d.minPrice);
                        initData['referBuyPrice'+i] = getPrice(d.referBuyPrice);
                    });
                    formSetVal('goodsForm', initData);
                });


                if (goodsVo.attrNameVoList.length > 0) {
                    $(".attr-div").css("display","block");
                    $("[name='moreAttr']").prop("checked",true);

                    //多属性支持
                    $.each(goodsVo.attrNameVoList, function (i,attrNameVo) {
                        initData[$("select[attrNameId='"+attrNameVo.id+"']").attr("name")]=attrNameVo.attrList[0].id;
                    });
                }

                //库存预警处理
                if (goodsVo.goodsHouseWarnList.length > 0) {
                    $.each(goodsVo.goodsHouseWarnList, function (i,houseWarn) {
                        $("[minHouseId='"+houseWarn.houseId+"']").val(getNumber(houseWarn.min));
                        $("[maxHouseId='"+houseWarn.houseId+"']").val(getNumber(houseWarn.max));
                    });
                }

                //初期信息处理
                if (goodsVo.goodsInitList.length > 0) {
                    let map = {};
                    $.each(goodsVo.initGoodsSnList, function (i,d) {
                        if (map[d.houseId] == undefined) {
                            map[d.houseId] = [];
                        }
                        map[d.houseId].push(d);
                    });

                    $.each(goodsVo.goodsInitList, function (i,goodsInit) {
                        $("[initNumHouseId='"+goodsInit.houseId+"']").val(getNumber(goodsInit.initNum));
                        $("[initCostHouseId='"+goodsInit.houseId+"']").val(getPrice(goodsInit.initCost));
                        $("[initAmtHouseId='"+goodsInit.houseId+"']").val(getPrice(goodsInit.initAmt));

                        let snList = map[goodsInit.houseId]==undefined ? []:map[goodsInit.houseId];
                        $("#"+goodsInit.houseId).attr("snList", JSON.stringify(snList));
                    });
                }

                initData.status = goodsVo.status;

                initData.remark = goodsVo.remark;
                initData.no = goodsVo.no;
                initData.name = goodsVo.name;
                initData.norms= goodsVo.norms;
                initData.status= goodsVo.status;
                initData.sn= "" + goodsVo.sn;
                formSetVal('goodsForm', initData);

                $("#goods-img").attr("imgName", goodsVo.image);
                $("#goods-img").attr("src", _baseUrl+"img/goods/"+goodsVo.image);
            });
        }

        function processCodeDiv() {
            var getTpl = codeTable.innerHTML;
            laytpl(getTpl).render(getGoods(), function(html){
                $("#code-div").empty().append(html);
            });
        }

        function processPriceDiv() {
            var getTpl = priceTable.innerHTML;
            laytpl(getTpl).render(getGoods(), function(html){
                $("#price-div").empty().append(html);
            });
        }
    });
}

function imgListener() {
//图片处理
    $(".select-img").click(function (e) {
        $("#image-file").click();
    });
    $("#image-file").change(function (e) {
        var files = this.files;
        var file;
        if (files && files.length) {
            file = files[0];
            if (!/^image\/\w+/.test(file.type)) {
                tip("请选择图片文件");
                return;
            }
        }

        if(file == undefined) {
            return;
        }

        var formData = new FormData();
        formData.append("imageFile", document.getElementById("image-file").files[0]);
        $(this).val("");
        $.ajax({
            url:_baseUrl+'goods/goods/uploadImg.action',
            type: 'post',
            cache: false,
            data: formData,
            processData : false,
            contentType : false,
            success : function(res) {
                $("#goods-img").attr("src",_baseUrl+"img/goods/"+res.data);
                $("#goods-img").attr("imgName",res.data);
                tip("上传成功");
            },
            error : function(res) {
                errTip("出错！！");
            }
        });
    });
}

function getCodeValue(codeName) {
    return getValue($('[name="'+codeName+'"]').val());
}

function getValue(value) {
    return emptyEntity(value) ? "" : value;
}

function getUnit(id) {
    var unit = {};

    let unitList= JSON.parse($("#data").attr("unitList"));
    $.each(unitList, function(i, d) {
        if (d.id == id) {
            unit = d;
        }
    });
    return unit;
}

function getUnitName(id) {
    var name = "";

    let unitList= JSON.parse($("#data").attr("unitList"));
    $.each(unitList, function(i, d) {
        if (d.id == id) {
            name = d.name;
        }
    });
    return name;
}

function setUnitList(unitList) {
    $("#data").attr("unitList", JSON.stringify(unitList));
}

function getUnitList() {
    let unitList= JSON.parse($("#data").attr("unitList"));
    return unitList;
}

function genUseMap() {
    let goodsSn_map = {};

    let goodsId = getGoods().id;
    if (goodsSn_map[goodsId] == undefined){
        goodsSn_map[goodsId] = [];
    }
    $(".snList").each(function (i,e) {
        $.each(JSON.parse($(e).attr("snList")), function (j,d) {
            goodsSn_map[goodsId].push(d);
        });
    });
    return goodsSn_map;
}

function getGoods() {
    let json = getFormJson($("form[lay-filter='goodsForm']"));
    return json;
}

/**
 * 序列号录入的回调函数
 * @param data
 */
function processSnImport(data) {
    $("#"+sn_button_houseId).attr("snList",JSON.stringify(data));
    $("#"+sn_button_houseId).find(".initNum").val(data.length);
}